package com.bml.architect.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bml.architect.sentinel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: baiml
 * @Title: SentenelController
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description: 原生的使用
 * @date: 2021/4/20 11:17
 */
@RestController
@RequestMapping("/sentinel")
public class Sentenel2Controller {


    @Autowired
    private UserService userService;

    @RequestMapping("/test")
    @SentinelResource(value = "sentinelTest", fallback = "fallback"
            , blockHandler = "handleException")
    public String test() {

        String msg = "hello sentinel!";
        System.out.println(msg);
        return msg;
    }



    @RequestMapping("/find1")
    public String findUser1(){
       return  userService.getUser();
    }

    @RequestMapping("/find2")
    public String findUser2(){
        return  userService.getUser();
    }

    public static String fallback(Throwable e){
        System.out.println("===被异常降级啦===");
        return "{'errcode:':'-2',msg:'===被异常降级啦==='}";
    }

    public static String handleException(BlockException e){
        System.out.println("===被限流啦===");
        return "{'errcode:':'-2',msg:'===被限流啦==='}";
    }

    /**
     * 初始化后添加规则
     */
//    @PostConstruct
//    public void init() {
//
//        List<FlowRule> rules = new ArrayList<>();
//        FlowRule rule = new FlowRule();
//        //设置受保护的资源
//        rule.setResource(RESOURCE_TEST);
//        // 设置流控规则 QPS
//        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        // 设置受保护的资源阈值
//        rule.setCount(1);
//
//        rules.add(rule);
//        FlowRuleManager.loadRules(rules);
//
//    }


}
